package com.heima.admin.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.AdUserDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if (StrUtil.isEmpty(adUserDto.getName()) || StrUtil.isEmpty(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名和密码不能为空");
        }

        LambdaQueryWrapper<AdUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(AdUser::getName,adUserDto.getName());
        AdUser adUser = getOne(lambdaQuery);
        if (ObjectUtil.isNotEmpty(adUser)){
            //当前用户存在
            //判断密码是否正确
            String password = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
            if (StrUtil.equals(password,adUser.getPassword())){
                //登录成功
                //生成token
                String token = AppJwtUtil.getToken(adUser.getId().longValue());
                HashMap<String, Object> map = new HashMap<>();
                //不能将密码和盐返回到客户端
                adUser.setPassword("");
                adUser.setSalt("");
                //封装token和用户信息
                map.put("token",token);
                map.put("user",adUser);

                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"密码错误");
            }
        }else {
            //用户不存在
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
    }

    public static void main(String[] args) {
        String s = DigestUtils.md5DigestAsHex(("123456" + "123abc").getBytes());
        System.out.println(s);
    }
}
